/**
 * 交易所工厂模块
 * 管理多个交易所的API服务
 */

const ApiService = require('./apiService'); // Upbit
const BinanceApiService = require('./binanceApiService');
const logger = require('../utils/logger');

class ExchangeFactory {
  constructor() {
    this.exchanges = new Map();
    this.supportedExchanges = {
      upbit: {
        name: 'Upbit',
        service: ApiService,
        enabled: true,
        description: 'Upbit 韩国交易所'
      },
      binance: {
        name: 'Binance',
        service: BinanceApiService,
        enabled: true,
        description: 'Binance 全球交易所'
      }
    };
  }

  /**
   * 初始化交易所服务
   * @param {Array} enabledExchanges - 启用的交易所列表
   */
  initialize(enabledExchanges = ['upbit', 'binance']) {
    logger.debug('🏭 初始化交易所服务工厂...');
    
    for (const exchangeId of enabledExchanges) {
      if (this.supportedExchanges[exchangeId]) {
        const exchangeConfig = this.supportedExchanges[exchangeId];
        const ServiceClass = exchangeConfig.service;
        const service = new ServiceClass();
        
        this.exchanges.set(exchangeId, {
          id: exchangeId,
          name: exchangeConfig.name,
          service: service,
          enabled: exchangeConfig.enabled,
          description: exchangeConfig.description
        });
        
        logger.debug(`✅ ${exchangeConfig.name} 服务已初始化`);
      } else {
        logger.warn(`⚠️  不支持的交易所: ${exchangeId}`);
      }
    }
    
    logger.info(`🏭 启用 ${this.exchanges.size} 个交易所: ${enabledExchanges.join(', ')}`);
  }

  /**
   * 获取所有启用的交易所
   * @returns {Array} 交易所配置数组
   */
  getEnabledExchanges() {
    return Array.from(this.exchanges.values()).filter(exchange => exchange.enabled);
  }

  /**
   * 获取特定交易所服务
   * @param {string} exchangeId - 交易所ID
   * @returns {Object|null} 交易所服务
   */
  getExchange(exchangeId) {
    const exchange = this.exchanges.get(exchangeId);
    return exchange ? exchange.service : null;
  }

  /**
   * 获取所有交易所的交易对数据
   * @returns {Promise<Object>} 按交易所分组的交易对数据
   */
  async fetchAllTradingPairs() {
    const results = {};
    const promises = [];
    
    for (const [exchangeId, exchange] of this.exchanges.entries()) {
      if (exchange.enabled) {
        promises.push(
          this.fetchExchangeTradingPairs(exchangeId)
            .then(pairs => ({ exchangeId, pairs, success: true }))
            .catch(error => ({ exchangeId, error: error.message, success: false }))
        );
      }
    }
    
    const settledResults = await Promise.allSettled(promises);
    
    for (const result of settledResults) {
      if (result.status === 'fulfilled') {
        const { exchangeId, pairs, error, success } = result.value;
        if (success) {
          results[exchangeId] = {
            pairs: new Set(pairs),
            count: pairs.length,
            success: true,
            timestamp: new Date().toISOString()
          };
          logger.debug(`✅ ${this.exchanges.get(exchangeId).name}: ${pairs.length} 个交易对`);
        } else {
          results[exchangeId] = {
            pairs: new Set(),
            count: 0,
            success: false,
            error: error,
            timestamp: new Date().toISOString()
          };
          logger.error(`❌ ${this.exchanges.get(exchangeId).name}: ${error}`);
        }
      }
    }
    
    return results;
  }

  /**
   * 获取单个交易所的交易对数据
   * @param {string} exchangeId - 交易所ID
   * @returns {Promise<Array>} 交易对数组
   */
  async fetchExchangeTradingPairs(exchangeId) {
    const exchange = this.exchanges.get(exchangeId);
    if (!exchange) {
      throw new Error(`未知的交易所: ${exchangeId}`);
    }
    
    if (!exchange.enabled) {
      throw new Error(`交易所 ${exchange.name} 未启用`);
    }
    
    return await exchange.service.fetchTradingPairs();
  }

  /**
   * 检查所有交易所的连接状态
   * @returns {Promise<Object>} 连接状态结果
   */
  async checkAllConnections() {
    const results = {};
    
    for (const [exchangeId, exchange] of this.exchanges.entries()) {
      if (exchange.enabled && exchange.service.checkConnection) {
        try {
          const isConnected = await exchange.service.checkConnection();
          results[exchangeId] = {
            connected: isConnected,
            name: exchange.name,
            timestamp: new Date().toISOString()
          };
        } catch (error) {
          results[exchangeId] = {
            connected: false,
            name: exchange.name,
            error: error.message,
            timestamp: new Date().toISOString()
          };
        }
      }
    }
    
    return results;
  }

  /**
   * 启用或禁用交易所
   * @param {string} exchangeId - 交易所ID
   * @param {boolean} enabled - 启用状态
   */
  setExchangeStatus(exchangeId, enabled) {
    const exchange = this.exchanges.get(exchangeId);
    if (exchange) {
      exchange.enabled = enabled;
      logger.info(`${enabled ? '启用' : '禁用'} ${exchange.name}`);
    } else {
      logger.warn(`未找到交易所: ${exchangeId}`);
    }
  }

  /**
   * 获取支持的交易所列表
   * @returns {Object} 支持的交易所配置
   */
  getSupportedExchanges() {
    return this.supportedExchanges;
  }

  /**
   * 获取交易所状态摘要
   * @returns {Object} 状态摘要
   */
  getStatusSummary() {
    const summary = {
      total: this.exchanges.size,
      enabled: 0,
      disabled: 0,
      exchanges: {}
    };
    
    for (const [exchangeId, exchange] of this.exchanges.entries()) {
      if (exchange.enabled) {
        summary.enabled++;
      } else {
        summary.disabled++;
      }
      
      summary.exchanges[exchangeId] = {
        name: exchange.name,
        enabled: exchange.enabled,
        description: exchange.description
      };
    }
    
    return summary;
  }
}

module.exports = ExchangeFactory;
